<template>
  <div class="hotel-performance-chart">
    <div class="hotel-performance-chart__header">
      <div class="hotel-performance-chart__title">Engagements Over Time</div>
      <div class="hotel-legend">
        <div class="hotel-legend__item hotel-legend__item--your-hotel">
          Your hotel
        </div>
        <div class="hotel-legend__item hotel-legend__item--hotel-1">
          Hotel 1
        </div>
        <div class="hotel-legend__item hotel-legend__item--hotel-2">
          Hotel 2
        </div>
        <div class="hotel-legend__item hotel-legend__item--hotel-3">
          Hotel 3
        </div>
        <div class="hotel-legend__item hotel-legend__item--hotel-4">
          Hotel 4
        </div>
        <div class="hotel-legend__item hotel-legend__item--hotel-5">
          Hotel 5
        </div>
      </div>
      <div class="chart-controls">
        <el-checkbox
          v-for="city in cityOptions"
          :label="city"
          :key="city"
          class="chart-controls__checkbox"
          v-model="checkedCities"
          @change="handleCheckedCitiesChange(checkedCities)"
          >{{ city }}</el-checkbox
        >

        <div class="chart-controls__refresh-container">
          <el-dropdown class="chart-controls__dropdown" trigger="click">
            <img
              src="@/assets/fresh.png"
              alt="Refresh"
              class="chart-controls__refresh-icon"
            />

            <el-dropdown-menu
              slot="dropdown"
              class="chart-controls__multi-select"
            >
              <el-checkbox-group
                style="display: flex; flex-direction: column; padding: 0 5px"
                v-model="selectedServices"
                @change="handleServiceSelectionChange"
              >
                <el-checkbox
                  v-for="service in serviceOptions"
                  :label="service.value"
                  :key="service.label"
                  >{{ service.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
    <!-- Chart display area -->
    <div class="hotel-performance-chart__graph">
      <PieChart :option="chartOptions" :height="'350px'"></PieChart>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import PieChart from "@components/common/PieChart.vue";

export default {
  components: {
    PieChart,
  },
  data() {
    return {
      cityAverageData: {
        "Avg of city": {
          name: "Avg of city",
          type: "line",
          symbol: "none",
          smooth: false,
          yAxisIndex: 0,
          lineStyle: {
            color: "#454545",
            width: 3,
            type: "dashed",
            dashOffset: 0,
            opacity: 1,
            dashArray: [15, 5],
          },
          data: [4, 4, 4, 4, 4, 4, 4, 4, 4],
        },
        "Avg of the competitors": {
          name: "Avg of the competitors",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#454545",
            width: 2,
            type: "dotted",
            dashOffset: 5,
            opacity: 0.9,
            dashArray: [1, 9],
          },
          data: [5, 5, 5, 5, 5, 5, 5, 5, 5],
        },
        "Avg of the portfolio": {
          name: "Avg of the portfolio",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#454545",
            width: 2,
            type: "dashed",
            dashOffset: 10,
            opacity: 0.9,
            dashArray: [5, 2, 1, 2],
          },
          data: [6, 6, 6, 6, 6, 6, 6, 6, 6],
        },
        "Avg of the brands": {
          name: "Avg of the brands",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#454545",
            width: 2,
            type: "dotted",
            dashOffset: 7,
            opacity: 0.9,
            dashArray: [3, 3],
          },
          data: [8, 8, 8, 8, 8, 8, 8, 8, 8],
        },
      },
      cityOptions: ["Previous Period"],
      previousPeriodData: [
        {
          name: "Previous Period (Blue)",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#0C3B7C",
            width: 1,
            type: "dashed",
            dash: [8, 4],
          },
          data: [5, 10, 8, 12, 10, 15, 12, 10, 8, 12, 10, 5],
        },
        {
          name: "Previous Period (Red)",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#FF0000",
            width: 1,
            type: "dashed",
            dash: [8, 4],
          },
          data: [1, 20, 3, 18, 2, 19, 1, 20, 4, 17, 2, 19],
        },
        {
          name: "Previous Period (Yellow)",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#FDDF1D",
            width: 1,
            type: "dashed",
            dash: [8, 4],
          },
          data: [5, 1, 15, 20, 3, 1, 18, 2, 16, 20, 4, 1],
        },
      ],
      serviceOptions: [
        { label: "Booking", value: "Booking" },
        { label: "Checkin", value: "Checkin" },
        { label: "Cleanness", value: "Cleanness" },
        { label: "Service", value: "Service" },
        { label: "Room", value: "Room" },
        { label: "Facilities", value: "Facilities" },
        { label: "F&B", value: "F&B" },
        { label: "Checkout", value: "CheckoutB" },
        { label: "Post saty", value: "Post saty" },
      ],
      selectedServices: [],
      timeSelect: "",
      showDropdown: false,
      clickTarget: null,
      checked: false,
      checkedCities: [],
      chartOptions: {
        subtitle: {
          text: "by scores",
        },
        grid: {
          left: "0%",
          right: "1%",
          bottom: "10%",
          top: "13%",
          containLabel: true,
        },
        legend: {
          orient: "horizontal",
          left: "30%",
          bottom: "0%",
          icon: "roundRect",
          itemWidth: 30,
          itemHeight: 5,
          itemGap: 40,
          borderWidth: 0,
          padding: [0, 0, 0, 10],
          data: [
            "Your Hotel",
            "Hotel 1",
            "Hotel 2",
            "Hotel 3",
            "Hotel 4",
            "Hotel 5",
          ],
          itemStyle: {
            borderRadius: 50, // 圆角半径（单位：像素）
          },
          textStyle: {
            color: "#6a6969",
            fontSize: 12,
            margin: 10,
              padding: [0, 5, 0, 5], // 控制文字与图标的间距 [上, 右, 下, 左]
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: [
            "Jan",
            "Feb",
            "Mar",
            "Apr",
            "May",
            "June",
            "July",
            "Aug",
            "Sept",
            "Oct",
            "Nov",
            "Dec",
          ],
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
            alignWithLabel: true,
          },
          axisLabel: {
            margin: 20,
            color: "#6a6969",
            fontSize: 12,
          },
        },
        yAxis: [
          {
            type: "value",
            axisTick: {
              inside: true,
              interval: 10,
            },
            axisLabel: {
              align: "right",
              margin: 27,
              color: "#6a6969",
              fontSize: 12,
              overflow: "truncate",
              fontWeight: 400,
              formatter: function (value) {
                return `${value}k`;
              },
            },
            name: "by # of voices",
            nameGap: 20,
            min: 0,
            max: 20,
            interval: 2,
            position: "left",
            splitLine: {
              show: false,
            },
            nameTextStyle: {
              fontSize: 14,
              fontWeight: 400,
            },
          },
        ],
        series: [
          {
            name: "Your hotel",
            symbol: "circle",
            symbolSize: 6,
            type: "line",
            data: [3, 8, 2, 15, 5, 18, 4, 12, 7, 16, 6, 10],
            yAxisIndex: 0,
            lineStyle: {
              color: "#6D03A1",
              width: 1,
            },
            itemStyle: {
              color: "#6D03A1",
            },
            emphasis: {
              lineStyle: {
                width: 6,
              },
            },
          },
          {
            name: "Hotel 1",
            type: "line",
            symbol: "circle",
            symbolSize: 6,
            data: [1, 12, 3, 20, 6, 16, 2, 14, 5, 18, 4, 11],
            yAxisIndex: 0,
            lineStyle: {
              color: "#A563EA",
              width: 1,
            },
            itemStyle: {
              color: "#A563EA",
            },
            emphasis: {
              lineStyle: {
                width: 6,
              },
            },
          },
          {
            name: "Hotel 2",
            symbol: "circle",
            symbolSize: 6,
            type: "line",
            data: [2, 5, 3, 7, 6, 10, 8, 12, 11, 15, 13, 16],
            yAxisIndex: 0,
            lineStyle: {
              color: "#2FAA68",
              width: 1,
            },
            itemStyle: {
              color: "#2FAA68",
            },
            emphasis: {
              lineStyle: {
                width: 6,
              },
            },
          },
          {
            name: "Hotel 3",
            symbol: "circle",
            symbolSize: 6,
            type: "line",
            data: [3, 6, 9, 12, 1, 4, 7, 10, 1, 15, 18, 5],
            yAxisIndex: 0,
            lineStyle: {
              color: "#4199E1",
              width: 1,
            },
            itemStyle: {
              color: "#4199E1",
            },
            emphasis: {
              lineStyle: {
                width: 6,
              },
            },
          },
          {
            name: "Hotel 4",
            symbol: "circle",
            symbolSize: 6,
            type: "line",
            data: [1, 5, 10, 15, 20, 18, 12, 5, 2, 10, 3, 1],
            yAxisIndex: 0,
            lineStyle: {
              color: "#3BD3DA",
              width: 1,
            },
            itemStyle: {
              color: "#3BD3DA",
            },
            emphasis: {
              lineStyle: {
                width: 6,
              },
            },
          },
          {
            name: "Hotel 5",
            symbol: "circle",
            symbolSize: 6,
            type: "line",
            data: [12, 11, 13, 1, 14, 12, 13, 20, 11, 12, 10, 14],
            yAxisIndex: 0,
            lineStyle: {
              color: "#EFB82C",
              width: 1,
            },
            itemStyle: {
              color: "#EFB82C",
            },
            emphasis: {
              lineStyle: {
                width: 6,
              },
            },
          },
        ],
      },
    };
  },
  mounted() {
    console.log("echarts:", echarts);

    if (!echarts) {
      throw new Error("ECharts 引入失败，请检查引入语句");
    }

    if (!this.chartOptions) {
      console.warn("ECharts option 为空，跳过初始化");
      return;
    }
    this.chart = echarts.init(this.$el);
    this.chart.setOption(this.chartOptions);

    this.chart.on("click", (params) => {
      if (params.seriesName.startsWith("Previous Period")) {
        console.log("点击了历史数据", params);
      }
    });

    document.addEventListener("click", this.handleOutsideClick);
    document.addEventListener("keydown", this.handleEscKey);
  },
  beforeUnmount() {
    document.removeEventListener("click", this.handleOutsideClick);
    document.removeEventListener("keydown", this.handleEscKey);
  },
  methods: {
    handleServiceSelectionChange(values) {
      console.log("选中的服务:", values);
    },

    handlePlatformSelect(service) {
      console.log("选择的服务:", service);
    },
    handleCheckedCitiesChange(checkedValues) {
      const avgOptions = checkedValues.filter(
        (option) => option !== "Previous Period"
      );
      const showHistory = checkedValues.includes("Previous Period");

      const originalSeriesNames = ["yellow", "red", "Booking", "purple"];
      const originalSeries = this.chartOptions.series.filter((series) =>
        originalSeriesNames.includes(series.name)
      );
      const avgSeries = Object.values(this.cityAverageData).filter((series) =>
        avgOptions.includes(series.name)
      );
      const historySeries = showHistory ? [...this.previousPeriodData] : [];
      const visibleSeries = [...originalSeries, ...avgSeries, ...historySeries];

      this.chartOptions = {
        ...this.chartOptions,
        series: visibleSeries,
      };

      console.log("预期的系列数量:", visibleSeries.length);
    },
  },
};
</script>

<style scoped lang="scss">
.hotel-performance-chart {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  padding: 16px 42px;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  border: 1px solid #cdcccc;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 5%);

  &__header {
    align-items: center;
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  &__title {
    font-size: 18px;
    font-weight: 600;
    color: #454545;
  }

  .hotel-legend {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 12px;

    &__item {
      padding: 8px;
      border-radius: 8px;
      font-size: 12px;
      font-weight: 400;
      color: #fff;
      white-space: nowrap;

      &--your-hotel {
        background-color: #6d03a1;
      }
      &--hotel-1 {
        background-color: #a563ea;
      }
      &--hotel-2 {
        background-color: #2faa68;
      }
      &--hotel-3 {
        background-color: #4199e1;
      }
      &--hotel-4 {
        background-color: #3bd3da;
      }
      &--hotel-5 {
        background-color: #efb82c;
      }
    }
  }

  .chart-controls {
    display: flex;
    align-items: center;

    &__checkbox {
      font-size: 14px;
      font-weight: 400;
      color: #232323;
      margin-right: 24px;
      white-space: nowrap;

      &:last-child {
        margin-right: 0;
      }

      ::v-deep .el-checkbox__inner {
        border: 1px solid #6a6969 !important;
      }
    }

    &__refresh-container {
      margin-left: 24px;
    }

    &__refresh-icon {
      cursor: pointer;
    }

    &__dropdown {
      position: relative;
    }
  }

  &__graph {
    width: 100%;
  }
}
:deep(.echarts-legend-icon) {
  border-radius: 5px !important;
}
</style>
